//
//  WH_HomeDetailController.m
//  App_6.23
//
//  Created by wanghao on 16/6/27.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_HomeDetailController.h"
#import "WH_HomeDetailHeard.h"
#import "WH_Home.h"
#import "WH_WebViewController.h"
#import "WH_HomeDetailCell.h"
#import "WH_PastViewController.h"
#import "WH_ShareOrderController.h"
#import "GiftTalkSheetView.h"
#import <Social/Social.h>
#import "AppDelegate.h"
#import "WH_DetailDuobaoView.h"
#import "WH_PersonalViewController.h"

@interface WH_HomeDetailController ()<UITableViewDataSource,UITableViewDelegate,GiftTalkSheetDelegate,UIScrollViewDelegate,WH_DetailDuobaoViewDelegate,UITextFieldDelegate>{
    
    NSArray  *titleArray;
    NSArray  *ImageArray;
    SLComposeViewController *slComposerSheet;
}

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) WH_HomeDetailHeard *detailHeaderV;
@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, assign) BOOL isUploading;
@property (nonatomic, strong) NSMutableArray *strArr;
@property (nonatomic, copy) NSString *webUrl;//图文详情
@property (nonatomic, copy) NSString *pastViewID;//往期
@property (nonatomic, strong) NSMutableArray *recordArr;
@property (nonatomic, copy) NSString *periodP;
@property (nonatomic, assign) NSInteger Datapage;
@property (nonatomic, strong) WH_DetailDuobaoView *duobaoV;

@end

@implementation WH_HomeDetailController

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
    [IQKeyboardManager sharedManager].enable = NO;

}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.tabBarController.tabBar setHidden:NO];
    [IQKeyboardManager sharedManager].enable = YES;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self createRightBtn];
    self.Datapage = 1;
    self.imageArr = [NSMutableArray array];
    self.recordArr = [NSMutableArray array];
    self.strArr = [NSMutableArray arrayWithObjects:@"图文详情", @"往期揭晓", @"晒单分享", nil];
    titleArray =
    @[@"FaceBook",@"Twitter"];
    ImageArray =
    @[@"facebook",@"Twitter"];
    
    [self createTab];
    [self bottomView];
    [self createHub];
    [self hubShow];
}

#pragma mark - rightBuuton

- (void)createRightBtn{
    
    UIView *customV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 25)];
    
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setImage:[[UIImage imageNamed:@"分享"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    backButton.frame = CGRectMake(35, 0, 25, 25);
    [backButton addTarget:self action:@selector(shareView) forControlEvents:UIControlEventTouchUpInside];
    backButton.tintColor = [UIColor blackColor];
    
    
    UIButton * bButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bButton.backgroundColor = [UIColor clearColor];
    [bButton setImage:[[UIImage imageNamed:@"购物车"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    bButton.frame = CGRectMake(0, 0, 25, 25);
    bButton.tintColor = [UIColor blackColor];
    [bButton addTarget:self action:@selector(toCart) forControlEvents:UIControlEventTouchUpInside];

    [customV addSubview:backButton];
    [customV addSubview:bButton];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customV];


}

#pragma mark - 创建视图

-(void)shareView{
    
    GiftTalkSheetView * gift = [[GiftTalkSheetView alloc]initWithTitleArray:titleArray
                                                                 ImageArray:ImageArray
                                                                 PointArray:nil
                                                               ActivityName:nil
                                                                   Delegate:self];
    [gift ShowInView:self.view];

}

#pragma mark  Gift&delegate
-(void)GiftTalkShareButtonAction:(NSInteger *)buttonIndex
{

    
    int index = (int)buttonIndex;
    if (index == 0) {
        NSLog(@"faceBook");

//        FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
//        content.contentURL = [NSURL URLWithString:@"http://y.bmstorez.com"];
//        content.contentTitle = self.faceTitle;
//        content.imageURL = [NSURL URLWithString:self.faceImage];
//        [FBSDKShareDialog showFromViewController:self
//                                     withContent:content
//                                        delegate:nil];
//
        [self faceBookShare];

    }else if (index == 1){
        
        [self twitterShare];

    }else{

    
    
    }
}

-(void)faceBookShare{
    //facebook分享
    if ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=6)
    {
        
        slComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
        [slComposerSheet setInitialText:_faceTitle];
        UIImageView *imageV = [UIImageView new];
        [imageV sd_setImageWithURL:[NSURL URLWithString:_faceImage]];
        [slComposerSheet addImage:imageV.image];
        
        [slComposerSheet addURL:[NSURL URLWithString:@"http://y.bmstorez.com"]];
        [self presentViewController:slComposerSheet animated:YES completion:nil];
    
        [slComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {
            NSLog(@"start completion block");
            NSString *output;
            switch (result) {
                case SLComposeViewControllerResultCancelled:
                    output = @"Action Cancelled";
                    break;
                case SLComposeViewControllerResultDone:
                    output = @"Post Successfull";
                    break;
                default:
                    break;
            }
            if ((result = SLComposeViewControllerResultCancelled))
            {

            
            }
        }];
        
    }
    else
    {
        //ios5.0极其以下的系统需要做的处理，可以直接弹出提示框
    }
    
}

-(void)twitterShare{
    //twitterShare分享
    if ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=6)
    {
        
        slComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
        [slComposerSheet setInitialText:_faceTitle];
        UIImageView *imageV = [UIImageView new];
        [imageV sd_setImageWithURL:[NSURL URLWithString:_faceImage]];
        [slComposerSheet addImage:imageV.image];
        
        [slComposerSheet addURL:[NSURL URLWithString:@"http://y.bmstorez.com"]];
        [self presentViewController:slComposerSheet animated:YES completion:nil];

        [slComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {
            NSLog(@"start completion block");
            NSString *output;
            switch (result) {
                case SLComposeViewControllerResultCancelled:
                    output = @"Action Cancelled";
                    break;
                case SLComposeViewControllerResultDone:
                    output = @"Post Successfull";
                    break;
                default:
                    break;
            }
            if ((result = SLComposeViewControllerResultCancelled))
            {
                
                
            }
        }];
        
    }
    else
    {
        //ios5.0极其以下的系统需要做的处理，可以直接弹出提示框
    }
    
}


-(void)createTab{
    
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.rowHeight = 50;
    self.myTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_myTableView];
    
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.equalTo(@0);
        make.bottom.equalTo(@-49);
    }];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[WH_HomeDetailCell class] forCellReuseIdentifier:@"WH_HomeDetailCell"];
    self.myTableView.sectionHeaderHeight = 10;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downLoadMJ)];
    self.myTableView.mj_header = header;
    [self.myTableView.mj_header beginRefreshing];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMJ)];
    self.myTableView.mj_footer = footer;

    [self.myTableView setHidden:YES];
}

-(void)bottomView{
    
    UIView *bottomView = [UIView new];
    bottomView.tag = 10011;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = [UIColor whiteColor];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(@0);
        make.bottom.mas_equalTo(@0);
        make.height.mas_equalTo(49);
    }];
    UIView *line = [UIView new];
    [bottomView addSubview:line];
    line.backgroundColor = [UIColor colorWithRed:0.86 green:0.85 blue:0.86 alpha:1];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.mas_equalTo(@0);
        make.height.mas_equalTo(@1);
    }];
    
    UIButton *duobaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:duobaoBtn];
    duobaoBtn.backgroundColor = [UIColor colorWithRed:0.86 green:0.21 blue:0.32 alpha:1];
    [duobaoBtn addTarget:self action:@selector(duobaoOrder:) forControlEvents:UIControlEventTouchUpInside];
    [duobaoBtn setTitle:@"立即夺宝" forState:UIControlStateNormal];
    [duobaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    duobaoBtn.layer.cornerRadius = 5;
    [duobaoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.mas_equalTo(6);
        make.bottom.mas_equalTo(@-6);
        make.width.equalTo(@(SCREEN_WIDTH/2-9));
    }];
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:addBtn];
    [addBtn addTarget:self action:@selector(addOrder:) forControlEvents:UIControlEventTouchUpInside];
    [addBtn setTitle:@"加入清单" forState:UIControlStateNormal];
    [addBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    addBtn.layer.cornerRadius = 5;
    addBtn.layer.borderWidth = .3;
    addBtn.layer.borderColor = [UIColor redColor].CGColor;
    [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.bottom.equalTo(duobaoBtn);
        make.right.mas_equalTo(@-6);
        make.left.equalTo(duobaoBtn.mas_right).offset(3);
    }];
    
    [bottomView setHidden:YES];

}
- (void)toLogin{
    
    //UIApplication是系统单例,可以直接使用
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    appDelegate.tabbarMain.selectedIndex = 3;
    
}

#pragma mark - 加入清单

-(void)addOrder:(UIButton *)btn{
    
    if ([ISLOGIN isEqualToString:@"1"]) {
        
        NSString *body =[NSString stringWithFormat:@"action=cart_add&user_id=%@&product_period=%@&product_num=1", NSUSERID,self.periodP] ;
        [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
            NSDictionary *dic = result;
            NSString *status = [dic objectForKey:@"status"];
            NSString *message = [dic objectForKey:@"message"];
            if ([status isEqualToString:@"success"]) {
                
                [WSProgressHUD showImage:nil status:@"加入成功"];
            }else{
                
                [WSProgressHUD showImage:nil status:message];
                
            }
            
        } failure:^(NSError *error) {
            
            
        }];
        
    }else{
        
        [self toLogin];
    }

}
#pragma mark - 购买视图

-(void)duobaoView{
    
    NSArray  *duobaoArray= [[NSBundle mainBundle]loadNibNamed:@"WH_DetailDuobaoView" owner:nil options:nil];
    _duobaoV = duobaoArray[0];
    _duobaoV.delegate = self;
    _duobaoV.countTF.delegate = self;
    _duobaoV.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    //立即购买页面
    _duobaoV.periodStr = _periodP;
    [[UIApplication sharedApplication].keyWindow addSubview:_duobaoV];
    //监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
#pragma mark - textField&&delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    //返回一个BOOL值，YES代表允许编辑，NO不允许编辑.
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if ([textField.text integerValue] > _detailHeaderV.shengyuC) {
        
        textField.text = [NSString stringWithFormat:@"%ld",(long)_detailHeaderV.shengyuC];
    }
    _duobaoV.moneyL.text = [NSString stringWithFormat:@"%@$",textField.text];
    
}
#pragma mark - Duobao&&Delegate

- (void)dismissBack:(id)result{
    
    //页面下移
    UITextField *textF = result;
    if ([textF isFirstResponder]) {
        [textF resignFirstResponder];
    }
    //延迟几秒
    [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionLayoutSubviews animations:^{
        
        _duobaoV.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);

    } completion:^(BOOL finished) {
        
        [_duobaoV removeFromSuperview];

    }];


    
}
- (void)pushTocart:(id)result{
    //去清单

    [self toCart];
    

}

- (void)toCart{
    
    //UIApplication是系统单例,可以直接使用
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    appDelegate.tabbarMain.selectedIndex = 2;
    [self.navigationController popToRootViewControllerAnimated:YES];

}

- (void)keyboardWillChangeFrameNotification:(NSNotification *)notification {
    
    //取出键盘动画的时间(根据userInfo的key----UIKeyboardAnimationDurationUserInfoKey)
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    //取到键盘的frame
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //计算控制器的view需要平移的距离
    CGFloat transformY = [[UIScreen mainScreen] bounds].size.height - keyboardFrame.origin.y;
    if (_duobaoV) {
        
        [UIView animateWithDuration:duration animations:^{
            
            _duobaoV.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - transformY);
            
        }];

    }

}
- (void)dealloc
{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    
}


#pragma mark - 立即夺宝

-(void)duobaoOrder:(UIButton *)btn{

    if ([ISLOGIN isEqualToString:@"1"]) {
        [self duobaoView];
        [UIView animateWithDuration:0.5 animations:^{
            
            _duobaoV.frame = CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT-20);
        }];

    }else{
        
        [self toLogin];
    }
    


}


#pragma mark - 刷新/加载

-(void)downLoadMJ{
    
    NSLog(@"下拉刷新");
    
    self.isUploading = NO;
    self.Datapage = 1;
    //[self postWorking];
    [self postData];
}

-(void)upLoadMJ
{
    NSLog(@"上拉加载");
    self.isUploading = YES;
    self.Datapage++;
    [self postData];
    
}

#pragma mark - Post

-(void)postData{

    NSString *body = [NSString stringWithFormat:@"action=product&product_id=%@",self.productID];
    NSLog(@"-----------%@",self.productID);
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        if (self.isUploading == NO){
            
            [self.imageArr removeAllObjects];
            [self.detailHeaderV removeFromSuperview];
        }

        NSDictionary *dic = result;
        NSDictionary *product_array = [dic objectForKey:@"product_array"];
        NSMutableArray *product_image_array = [product_array objectForKey:@"product_image_array"];
        NSLog(@"-------%ld",(unsigned long)product_image_array.count);
        
        if (product_image_array.count != 0) {
            //Facebook
            self.faceImage = product_image_array[0];
        }
        WH_Home *homeDetail = [WH_Home modelWithDictionary:product_array];
        self.detailHeaderV = [[WH_HomeDetailHeard alloc] initWithFrame:CGRectMake(0, 0, self.myTableView.frame.size.width, 420)];
        self.myTableView.tableHeaderView = _detailHeaderV;
        [self.detailHeaderV createModel:homeDetail];
        [self.detailHeaderV createSubViews:product_image_array];
        //Facebook
        self.faceTitle = homeDetail.product_name;
        self.webUrl = homeDetail.product_description;
        self.pastViewID = homeDetail.product_id;
        //加入清单赋值
        self.periodP = homeDetail.product_period;
        
        [self postRecord:homeDetail.product_period];
        [self endFresh];
        [self.myTableView setHidden:NO];
        UIView *botV = [self.view viewWithTag:10011];
        [botV setHidden:NO];
        [self hubDismiss];
    } failure:^(NSError *error) {
        

    }];
    
}

-(void)postRecord:(NSString *)period{
    
    NSString *body = [NSString stringWithFormat:@"action=product_record&product_id=%@&product_period=%@&page=%ld",self.productID,period, self.Datapage];
    NSLog(@"%@%@",self.productID,period);
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        NSLog(@"=====%@",result);
        if (self.isUploading == NO){
            
            [self.recordArr removeAllObjects];
        }

        NSDictionary *dic = result;
        NSArray *product_record_array = [dic objectForKey:@"product_record_array"];
        
        for (NSDictionary *dic in product_record_array) {
            
            WH_Home *record = [WH_Home modelWithDictionary:dic];
            [self.recordArr addObject:record];
        }
        [self.myTableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];
    
}
#pragma mark - 结束刷新

-(void)endFresh{
    
    [self.myTableView.mj_footer endRefreshing];
    [self.myTableView.mj_header endRefreshing];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return self.strArr.count;
    }
    return self.recordArr.count+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indexCell = @"cell";
    static NSString *homeDetail = @"WH_HomeDetailCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indexCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        
        cell.textLabel.text = self.strArr[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if(indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            
            cell.textLabel.text = @"所有参与记录";
            cell.accessoryType = UITableViewCellAccessoryNone;

        }else{
            
            WH_HomeDetailCell *detailcell = [tableView dequeueReusableCellWithIdentifier:homeDetail];
            
            detailcell.record = self.recordArr[indexPath.row-1];
            return detailcell;
        }
    }
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    headview.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1];
    return headview;
}
#pragma mark - scrollDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGFloat sectionHeaderHeight = 40;
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            WH_WebViewController *webView = [[WH_WebViewController alloc] init];
            webView.urlStr = self.webUrl;
            [self.navigationController pushViewController:webView animated:YES];
        }else if (indexPath.row == 1){
            
            WH_PastViewController *pastVC = [[WH_PastViewController alloc] init];
            pastVC.pastID = self.pastViewID;
            [self.navigationController pushViewController:pastVC animated:YES];
            
        }else if (indexPath.row == 2){
            
            WH_ShareOrderController *shareVC = [[WH_ShareOrderController alloc] init];
            shareVC.showID = self.pastViewID;
            
            [self.navigationController pushViewController:shareVC animated:YES];

        }
        
    }else{
        
        WH_PersonalViewController *personVC = [[WH_PersonalViewController alloc] init];
        WH_Home *personH = self.recordArr[indexPath.row-1];
        personVC.personID = personH.user_id;
        personVC.personImg = personH.user_avatar;
        personVC.personName = personH.user_name;
        [self.navigationController pushViewController:personVC animated:YES];
    }

    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
